package com.css.fxfzypg.modules.surveytaskmanage.service.impl;

import com.css.fxfzypg.base.user.service.impl.UserServiceImpl;
import com.css.fxfzypg.base.user.viewobjects.UserBaseInfoVO;
import com.css.fxfzypg.modules.group.entity.GroupEntity;
import com.css.fxfzypg.modules.group.entity.GroupUserEntity;
import com.css.fxfzypg.modules.group.entity.UserEntity;
import com.css.fxfzypg.modules.group.service.GroupUserService;
import com.css.fxfzypg.modules.group.service.impl.GroupServiceImpl;
import com.css.fxfzypg.modules.group.service.impl.GroupUserServiceimpl;
import com.css.fxfzypg.modules.group.vo.GroupMemberVo;
import com.css.fxfzypg.modules.group.vo.GroupVo;
import com.css.fxfzypg.modules.preassesstaskmanage.vo.PreAssessVo;
import com.css.fxfzypg.modules.surveytaskmanage.entity.FieldSurveyTaskEntity;
import com.css.fxfzypg.modules.surveytaskmanage.repository.FieldSurveyTaskRepository;
import com.css.fxfzypg.modules.surveytaskmanage.service.FieldSurveyTaskService;
import com.css.fxfzypg.modules.surveytaskmanage.vo.FieldSurveyTaskGroupVo;
import com.css.fxfzypg.modules.surveytaskmanage.vo.FieldSurveyTaskVo;
import com.css.fxfzypg.modules.surveytaskmanage.vo.FieldSurveyVo;
import com.css.fxfzypg.modules.surveytaskmanage.vo.TaskVo;
import com.css.fxfzypg.util.*;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.impl.SUserServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author
 * @program
 * @description
 * @create 2022/7/26 10:30
 **/
@Service
public class FieldSurveyTaskServiceImpl implements FieldSurveyTaskService {

    @Autowired
    FieldSurveyTaskRepository fieldSurveyTaskRepository;

    @Autowired
    SUserServiceImpl sUserServiceImpl;

    @Autowired
    GroupServiceImpl groupServiceImpl;

    @Autowired
    GroupUserServiceimpl groupUserServiceimpl;

    @Autowired
    GroupUserService groupUserService;

    /**
     * 新建任务
     * @param
     * @return
     */
    @Override
    public String saveTask(FieldSurveyTaskVo fieldSurveyTaskVo) {
        FieldSurveyTaskEntity parentTask = fieldSurveyTaskVo.getParentTask();
        String userId = PlatformSessionContext.getUserID();
        String parentTaskId = UUIDGenerator.getUUID();
        parentTask.setDelFlag("0");
        parentTask.setCreateUser(userId);
        parentTask.setCreateTime(new Date());
        //获取用户名称
        String sUser = sUserServiceImpl.getSUser(userId);
        SUser userInfo = CreateGson.createGson().fromJson(sUser, SUser.class);
        String userName=userInfo.getUserName();
        parentTask.setTaskManager(userName);
        parentTask.setId(parentTaskId);
        parentTask.setParentId("0");

        if(PlatformObjectUtils.isEmpty(parentTask.getGroupId())){
            parentTask.setTaskStatus("0");
        }else{
            parentTask.setTaskStatus("1");
        }

        FieldSurveyTaskEntity subTask = fieldSurveyTaskVo.getSubTask();
        if(!PlatformObjectUtils.isEmpty(subTask)){

                subTask.setDelFlag("0");
                subTask.setCreateUser(userId);
                subTask.setCreateTime(new Date());
                //获取用户名称
                subTask.setTaskManager(userName);
                subTask.setId(UUIDGenerator.getUUID());
                subTask.setParentId(parentTaskId);
                subTask.setParentTask(parentTask.getTaskNum());
                if(PlatformObjectUtils.isEmpty(subTask.getGroupId())){
                    subTask.setTaskStatus("0");
                }else{
                    parentTask.setTaskStatus("1");
                    subTask.setTaskStatus("1");
                }
                fieldSurveyTaskRepository.saveTask(subTask);

        }
        fieldSurveyTaskRepository.saveTask(parentTask);
        return parentTaskId;
    }

    @Override
    public void saveSubTask(FieldSurveyTaskEntity subTask) {
        if(!PlatformObjectUtils.isEmpty(subTask)){
            subTask.setDelFlag("0");
            subTask.setCreateUser(PlatformSessionContext.getUserID());
            subTask.setCreateTime(new Date());
            //获取用户名称PlatformSessionContext.getUserID()
            String sUser = sUserServiceImpl.getSUser(PlatformSessionContext.getUserID());
            SUser userInfo = CreateGson.createGson().fromJson(sUser, SUser.class);
            subTask.setTaskManager(userInfo.getUserName());
            subTask.setId(UUIDGenerator.getUUID());
            if(PlatformObjectUtils.isEmpty(subTask.getGroupId())){
                subTask.setTaskStatus("0");
            }else{
                fieldSurveyTaskRepository.completeTask("1",subTask.getParentId());
                subTask.setTaskStatus("1");
            }
            fieldSurveyTaskRepository.saveTask(subTask);
        }
    }

    @Override
    public Map<String,Object> getPage(TaskVo taskVo,int curPage, int pageSize) {
        taskVo.setCreateUser(PlatformSessionContext.getUserID());
        Map<String,Object> parentTask=fieldSurveyTaskRepository.findParentIdByTask("0",taskVo,curPage,pageSize);
        List<FieldSurveyVo> tasks = (List<FieldSurveyVo>) parentTask.get("rows");
        for(FieldSurveyVo task:tasks){
            List<FieldSurveyVo> subTasks=getSubTasks(task.getId(),taskVo);
            task.setChildren(subTasks);
        }
        return parentTask;
    }
    private List<FieldSurveyVo> getSubTasks(String id,TaskVo taskVo) {
        List<FieldSurveyVo> tasks=fieldSurveyTaskRepository.findSubIdByTask(id,taskVo);
        if(tasks!=null) {
            for(FieldSurveyVo task:tasks) {
                String id1 = task.getId();
                List<FieldSurveyVo> subTask=fieldSurveyTaskRepository.findSubIdByTask(id1,taskVo);
                task.setChildren(subTask);
            }
        }
        return tasks;
    }

    @Override
    public List<FieldSurveyTaskEntity> getSubTask(String parentTaskId) {
        List<FieldSurveyTaskEntity> subTaskList=fieldSurveyTaskRepository.getSubTask(parentTaskId);
        return subTaskList;
    }

    @Override
    public FieldSurveyTaskGroupVo findById(String taskId) {
        FieldSurveyTaskGroupVo fieldSurveyTaskGroupVo=new FieldSurveyTaskGroupVo();
        FieldSurveyTaskEntity fieldSurveyTaskEntity=fieldSurveyTaskRepository.findById(taskId);
        fieldSurveyTaskGroupVo.setPreAssessTaskEntity(fieldSurveyTaskEntity);
        List<UserEntity> memberList=new ArrayList<>();
        List<UserEntity> expertList=new ArrayList<>();
        List<GroupUserEntity> groupUserEntityList=groupUserService.selectGroupMemberAndGroupExpert(fieldSurveyTaskEntity.getGroupId());
        for(GroupUserEntity groupUserEntity:groupUserEntityList){
            String groupUserInfo = sUserServiceImpl.getGroupUserInfo(groupUserEntity.getUserId());
            UserEntity userInfo = CreateGson.createGson().fromJson(groupUserInfo, UserEntity.class);
            if("0".equals(groupUserEntity.getRole())){
                memberList.add(userInfo);
            }else{
                expertList.add(userInfo);
            }
        }
        fieldSurveyTaskGroupVo.setMemberlist(memberList);
        fieldSurveyTaskGroupVo.setExpertlist(expertList);
        return fieldSurveyTaskGroupVo;
    }

    @Override
    public void updateTask(FieldSurveyTaskEntity fieldSurveyTaskEntity) {
        fieldSurveyTaskEntity.setUpdateUser(PlatformSessionContext.getUserID());
        fieldSurveyTaskEntity.setUpdateTime(new Date());
        /*if(!PlatformObjectUtils.isEmpty(fieldSurveyTaskEntity.getGroupId())){
            fieldSurveyTaskEntity.setTaskStatus("1");
            if(!"0".equals(fieldSurveyTaskEntity.getParentId())){
                fieldSurveyTaskRepository.completeTask("1",fieldSurveyTaskEntity.getParentId());
            }
        }*/
        fieldSurveyTaskRepository.updateTask(fieldSurveyTaskEntity);
    }

    @Override
    public Boolean whetherHaveSubTask(List<String> list) {
        for(String id:list){
            FieldSurveyTaskEntity fieldSurveyTaskEntity = fieldSurveyTaskRepository.findById(id);
            if("0".equals(fieldSurveyTaskEntity.getParentId())){
                List<FieldSurveyTaskEntity> subTaskList = fieldSurveyTaskRepository.getSubTask(fieldSurveyTaskEntity.getId());
                if(!PlatformObjectUtils.isEmpty(subTaskList)){
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void completeTask(List<String> ids) {
        String taskStatus="2";
        for(String id:ids){
            FieldSurveyTaskEntity task = fieldSurveyTaskRepository.findById(id);
            fieldSurveyTaskRepository.completeTask(taskStatus,id);
            if("0".equals(task.getParentId())){
                List<FieldSurveyTaskEntity> subTasks = fieldSurveyTaskRepository.getSubTask(task.getParentId());
                for(FieldSurveyTaskEntity subTask:subTasks){
                    fieldSurveyTaskRepository.completeTask(taskStatus,subTask.getId());
                }
            }else {
                FieldSurveyTaskEntity parentTask = fieldSurveyTaskRepository.findById(task.getParentId());
                fieldSurveyTaskRepository.completeTask(taskStatus,parentTask.getId());
            }

        }
    }

    @Override
    @Transactional
    public void assignGroup(FieldSurveyTaskEntity fieldSurveyTaskEntity) {
        fieldSurveyTaskEntity.setUpdateUser(PlatformSessionContext.getUserID());
        fieldSurveyTaskEntity.setUpdateTime(new Date());
        if(!PlatformObjectUtils.isEmpty(fieldSurveyTaskEntity.getGroupId())){
            fieldSurveyTaskEntity.setTaskStatus("1");
            if(!"0".equals(fieldSurveyTaskEntity.getParentId())){
                fieldSurveyTaskRepository.completeTask("1",fieldSurveyTaskEntity.getParentId());
            }
        }
        fieldSurveyTaskRepository.assignGroup(fieldSurveyTaskEntity);
    }

    @Transactional
    @Override
    public void deleteTask(List<String> list) {
        for(String id:list){
            FieldSurveyTaskEntity fieldSurveyTaskEntity = fieldSurveyTaskRepository.findById(id);
            if("0".equals(fieldSurveyTaskEntity.getParentId())){
                List<FieldSurveyTaskEntity> subTaskList = fieldSurveyTaskRepository.getSubTask(fieldSurveyTaskEntity.getId());
                if(!PlatformObjectUtils.isEmpty(subTaskList)){
                    for(FieldSurveyTaskEntity subTask:subTaskList){
                        fieldSurveyTaskRepository.deleteFieldSurvey("1",subTask.getTaskNum());
                        fieldSurveyTaskRepository.deleteTask("1",subTask.getId());
                    }
                }
            }
            fieldSurveyTaskRepository.deleteFieldSurvey("1",fieldSurveyTaskEntity.getTaskNum());
            fieldSurveyTaskRepository.deleteTask("1",fieldSurveyTaskEntity.getId());
        }
    }

    @Override
    public String getSubTaskDistrict(List<String> taskDistricts) {
        StringBuilder str=new StringBuilder();
        for(String taskDistrict:taskDistricts){
            if(taskDistrict.indexOf("省")!=-1){
                str.append(taskDistrict+",");
            }else if("北京市".equals(taskDistrict) || "天津市".equals(taskDistrict) || "上海市".equals(taskDistrict) || "重庆市".equals(taskDistrict)){
                str.append(taskDistrict+",");
            }
        }
        String subTaskDistrict = str.substring(0, str.lastIndexOf(","));
        return subTaskDistrict;
    }

    @Override
    public Map<String, Object> getAppPage(HttpServletRequest request, TaskVo taskVo, int curPage, int pageSize) {
        String userId=taskVo.getUserId();
        GroupEntity GroupEntity=groupServiceImpl.getGroupInfo(userId);
        List<String> grouoIds=new ArrayList<>();
        if(PlatformObjectUtils.isEmpty(GroupEntity)){
            List<GroupUserEntity> groupUserEntitys=groupUserServiceimpl.getGroupId(userId);
            for(GroupUserEntity groupUserEntity:groupUserEntitys){
                grouoIds.add(groupUserEntity.getGroupId());
            }
        }else{
            grouoIds.add(GroupEntity.getId());
            List<GroupUserEntity> groupUserEntitys=groupUserServiceimpl.getGroupId(userId);
            for(GroupUserEntity groupUserEntity:groupUserEntitys){
                grouoIds.add(groupUserEntity.getGroupId());
            }
        }
        Map<String, Object> page = fieldSurveyTaskRepository.getAppPage(request, taskVo, curPage, pageSize,grouoIds);
        return page;
    }

    @Override
    public String getSubTaskCode(String parentTaskNum) {
        StringBuilder stringBuilder = new StringBuilder(parentTaskNum+"-");
        String subNum="";
        DecimalFormat decimalFormat=new DecimalFormat("000");
        FieldSurveyTaskEntity parentTask=fieldSurveyTaskRepository.getParentTask(parentTaskNum);
        if(!PlatformObjectUtils.isEmpty(parentTask)){
            List<FieldSurveyTaskEntity> subTask = fieldSurveyTaskRepository.getSubTask(parentTask.getId());
            if(!PlatformObjectUtils.isEmpty(subTask)){
                String maxSubTaskCNum=fieldSurveyTaskRepository.getMaxSubTaskCNum(parentTaskNum);
                String str = maxSubTaskCNum.substring(11, maxSubTaskCNum.length());
                int i = Integer.parseInt(str)+1;
                subNum=decimalFormat.format(i);
            }else{
                int i = 1;
                subNum=decimalFormat.format(i);
            }
        }else{
            int i = 1;
            subNum=decimalFormat.format(i);
        }
        return stringBuilder.append(subNum).toString();
    }
}
